#!/usr/bin/python

# 1/9/12 TODO:
   # - opencv -> pyside QImage conversion
   # - QImage as center widget
   # Pyside getting mouse params?

import sys
from PySide.QtCore import *
from PySide.QtGui import *


class Display(State):
    def __init__(self, image):
        print("[DISPLAY] init: "+image)
        State.__init__(self,
                       outcomes=['succeeded', 'failed'],
                       output_keys=['low', 'high'])
    def execute(self, userdata):
        print("[DISPLAY] execute")
        self.active = True
        self.done = False

        while not self.done or self.start_x == self.end_x or self.start_y == self.end_y:
            sleep(0.01)

        self.active = False
        cv.DestroyWindow(self.window_name)

        # Pass on the selected rectangle to the next state
        userdata.low = (min(self.start_x, self.end_x), min(self.start_y, self.end_y))
        userdata.high = (max(self.start_x, self.end_x), max(self.start_y, self.end_y))

        return 'succeeded'

class MainWindow(QMainWindow):
   def __init__(self):
      super(MainWindow, self).__init__()
      self.textEdit = QTextEdit()
      self.setCentralWidget(self.textEdit)
      self.textEdit.setMaximumWidth(1000)
      
      dock = QDockWidget("dock", self)
      dock.setAllowedAreas(Qt.RightDockWidgetArea)
      self.button = QPushButton("Click me!")
      self.button.clicked.connect(self.hello)
      dock.setWidget(self.button)
      self.addDockWidget(Qt.RightDockWidgetArea, dock)

      self.window_name = 'Select knob region'
      self.topic_name = image

      self.start_x = 0
      self.start_y = 0
      self.end_x = 0
      self.end_y = 0
      self.outlining = False

      self.active = False
      self.done = False

      self.bridge = CvBridge()
      self.image_sub = rospy.Subscriber(image, Image, self.image_callback)


   def hello(self):
      print "Hello"

   def image_callback(self, image):
      print("[DISPLAY] image_callback. Topic: "+self.topic_name)
      if self.active:
          # Convert the ROS image message to an OpenCV image.
          try:
              cv_image = self.bridge.imgmsg_to_cv(image)
          except CvBridgeError, e:
              print e
                
          cv.Rectangle(cv_image, (self.start_x, self.start_y), (self.end_x, self.end_y), (0, 255, 0), 1)
           
          #cv.ShowImage(self.window_name, cv_image)
          cv.SetMouseCallback(self.window_name, self.mouse_callback)
          if cv.WaitKey(10) != -1:
              print 'done'
              self.done = True

    def mouse_callback(self, event, x, y, flags, param):
       print("[DISPLAY] mouse_callback")
       if event == cv.CV_EVENT_LBUTTONDOWN:
          self.start_x = x
          self.start_y = y
          self.end_x = x
          self.end_y = y            
          self.outlining = True
       elif event == cv.CV_EVENT_MOUSEMOVE and self.outlining:
          self.end_x = x
          self.end_y = y
       elif event == cv.CV_EVENT_LBUTTONUP:
          self.outlining = False


if __name__ == '__main__':
   app = QApplication(sys.argv)
   main_window = MainWindow()
   main_window.showMaximized()
   main_window.show()
   sys.exit(app.exec_())


